package com.aspire.boc.mms.wmf.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.swing.ImageIcon;

import org.apache.log4j.Logger;

import com.huawei.insa2.comm.cmpp.message.CMPPMessage;
import com.huawei.insa2.comm.cmpp30.message.CMPP30SubmitMessage;
import com.huawei.insa2.comm.cmpp30.message.CMPP30SubmitRepMessage;

/**
 * @author shining
 * @version 2008-7-9 18:27:43
 */
public class Util {

	static Logger logger = Logger.getLogger(Util.class);

	static ResourceManager rm = ResourceManager.getInstance();

	/**
	 * 发送邮件
	 * 
	 * @param tomail
	 *            String 接收方
	 * @param content
	 *            String 发送内容
	 */
	public static void sendMail(String tomail, String content, String subject) {
		Properties props = new Properties();
		String fromMail = rm.getValue("sendMail.fromMail");
		// String userName = rm.getValue("sendMail.userName");
		// String password = rm.getValue("sendMail.password");
		String host = rm.getValue("sendMail.host");
		String port = rm.getValue("sendMail.port");
		// logger.info("[fromMail:" + fromMail + "][userName:" + userName
		// + "][password:" + password + "][host:" + host + "][port:"
		// + port + "]");
		props.put("mail.smtp.user", fromMail);
		props.put("mail.smtp.host", host);
		props.put("mail.smtp.port", port);
		props.put("mail.smtp.starttls.enable", "true");
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.socketFactory.port", port);
		props.put("mail.smtp.socketFactory.fallback", "false");
		// Socket
		props.put("mail.smtp.connectiontimeout", "10000");
		// Socket
		props.put("mail.smtp.timeout", "10000");
		try {
			Authenticator auth = new SMTPAuthenticator();
			Session session = Session.getInstance(props, auth);
			MimeMessage msg = new MimeMessage(session);
			msg.setText(content);
			msg.setSubject(subject);
			msg.setFrom(new InternetAddress(fromMail));
			msg.addRecipient(Message.RecipientType.TO, new InternetAddress(
					tomail));
			Transport.send(msg);
			logger.info("send mail success[" + tomail + "]");
		} catch (Exception e) {
			logger.error("send mail to " + tomail + " error:" + e);
		}
	}

	/**
	 * 下发短信
	 * 
	 * @param mobile
	 *            String 手机号
	 * @param content
	 *            String 发送内容
	 */
	public static void sendSMSSocket(String mobile, String content) {
		String[] dest = { mobile };
		int end = 0;
		MySMProxy30 mySMProxy = MySMProxy30.getInstance();
		CMPP30SubmitMessage submitMsg = null;
		CMPPMessage submitRepMsg = null;
		int limit = Integer.parseInt(rm.getValue("sms.size.max"));
		String srcid = rm.getValue("sms.srcid");
		String serviceid = rm.getValue("sms.serviceid");
		String spid = rm.getValue("sms.spid");
		int length = content.length();
		int count = 1;
		if (length % limit == 0)
			count = length / limit;
		else
			count = length / limit + 1;
		for (int j = 0; j < count; j++) {
			if ((j + 1) * limit > length)
				end = length;
			else
				end = (j + 1) * limit;
			String subcontent = content.substring(j * limit, end);
			try {
				submitMsg = new CMPP30SubmitMessage(1, 1, 0, 5, serviceid, 3,
						mobile, 0, 0, 0, 15, spid, "01", "0", null, null,
						srcid, dest, 0, subcontent.getBytes(), "");
				logger.info("submitMsg:" + submitMsg);
				submitRepMsg = mySMProxy.send(submitMsg);
				logger.info("submitRepMsg:" + submitRepMsg);
				CMPP30SubmitRepMessage crm = (CMPP30SubmitRepMessage) submitRepMsg;
				ByteBuffer buffer = ByteBuffer.wrap(crm.getMsgId());
				long msgId = buffer.getLong();
				logger.info("gateway response sequenceId:"
						+ crm.getSequenceId() + " result:" + crm.getResult()
						+ "  msgId:" + msgId);
				logger.info("[send sms][" + mobile + "][" + subcontent + "]["
						+ crm.getResult() + "]");
			} catch (Exception e) {
				logger.error("sendSMSSocket", e);
			}
		}
	}

	public static void writeGif(File file, BufferedImage image)
			throws Exception {
		FileOutputStream out = null;
		try {
			out = new FileOutputStream(file);
			// AnimatedGifEncoder e = new AnimatedGifEncoder();
			// e.start(out);
			// e.setDelay(0); // 1 frame per sec
			// e.addFrame(image);
			// e.finish();
			GIFEncoder gife = new GIFEncoder(image);
			gife.Write(out);
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("writeGif error!");
		}
	}

	public static void makeLabelImage(String sfile, String dfile,
			String labelName) {
		// 初始化长度
		int l = 85;
		int s1_cl = 0;
		for (char c : labelName.toCharArray()) {
			if (isChinese(c)) {
				s1_cl = s1_cl + 7;
			}
			s1_cl = s1_cl + 7;
		}
		l = s1_cl + 31;
		// 初始化 黑板的长 高
		BufferedImage bufImg = new BufferedImage(l, 23,
				BufferedImage.TYPE_INT_RGB);
		Graphics2D graphics = bufImg.createGraphics();
		// background
		graphics.setColor(new Color(255, 255, 255));
		// 白板的 长 高
		graphics.fillRect(0, 0, l, 30);
		// 画水印图
		// 读取标签图片

		ImageIcon waterIcon = new ImageIcon(sfile);
		Image waterImg = waterIcon.getImage();
		graphics.drawImage(waterImg, 4, 4, null);
		/***********************************************************************
		 * 生成文字
		 */
		// set font Times New Roman Simsun
		// graphics.setFont(new Font("Times New Roman", Font.BOLD, 12));
		graphics.setFont(new Font("Simsun", Font.BOLD, 12));
		graphics.setColor(Color.BLACK);
		// water code
		// 开始位置 上下位置
		graphics.drawString(labelName, 25, 15);
		// graphics.setFont(new Font("Simsun", Font.PLAIN, 12));
		// graphics.drawString(s2, 50, 15);
		graphics.dispose();
		logger.info(sfile + "--------" + dfile + "----------" + labelName
				+ "-----");
		/**
		 * 
		 * 
		 */
		FileOutputStream out = null;
		try {
			out = new FileOutputStream(dfile);
			GIFEncoder gife = new GIFEncoder(bufImg);
			gife.Write(out);
		} catch (Exception e) {
			logger.info(e);

		}
	}

	private static boolean isChinese(char a) {
		int v = (int) a;
		return (v >= 19968 && v <= 171941);
	}

	public static String getMD5(String str) {
		MessageDigest digest = null;
		try {
			digest = MessageDigest.getInstance("MD5");
			digest.update(str.getBytes());

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		BigInteger bigInt = new BigInteger(1, digest.digest());
		return bigInt.toString(16);
	}
	
	/**
     * @Description 将Date转成"yyyyMMdd"8位字符串
     * @param date
     * @return
     */
    public static String convertDateToString(Date date) {
        String dateFormat = "yyyyMMdd";
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        String dateStr = sdf.format(date);
        return dateStr;
    }
    
    /**
     * @description 按“MMddHHmmssSSS”格式返回当前时间戳
     * @return
     */
    public static String getCurrentTimestamp() {

        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat sdf = new SimpleDateFormat("MMddHHmmssSSS");
        String timestampStr = sdf.format(date);
        return timestampStr;
    }
    
}
